package book;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class udpClint_book {
    DatagramSocket socket;
    int port;//目的端口号
    String ip;//目的ip

    public udpClint_book(String ip, int port) {
        this.ip = ip;
        this.port = port;
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }

    public void start() {
        while (true) {
            Scanner in = new Scanner(System.in);
            try {
                //请求
                String req = in.nextLine();

                //将请求包装 和服务器包装的方式相同
                DatagramPacket packet = new DatagramPacket(req.getBytes(),
                        0, req.length(),InetAddress.getByName(ip), port);

                //将包装好了的包发送
                socket.send(packet);

                //接收返回的请求
                DatagramPacket receive = new DatagramPacket(new byte[1024], 1024);
                //接收请求
                socket.receive(receive);
                //将响应处理
                String msg = new String(receive.getData(), 0, receive.getLength());
                //打印
                System.out.println(msg);

            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        udpClint_book book = new udpClint_book("127.0.0.1", 8888);
        book.start();
    }
}
